package com.ffapp.f9164.td.fragment.passageway;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.clj.fastble.utils.BleLog;
import com.clj.fastble.utils.HexUtil;
import com.ffapp.f9164.td.R;
import com.ffapp.f9164.td.basis.BasisFragment;
import com.ffapp.f9164.td.bean.ParamListData;
import com.ffapp.f9164.td.util.EditTextUtil;
import com.suke.widget.SwitchButton;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class DIAlarmFragment extends BasisFragment {

    private String atShowString;
    private int viewPagerCurrentItem;

    @BindView(R.id.recyclerview)
    RecyclerView recyclerView;
    MyAdapter adapter;
    ArrayList<ParamListData> submitList = new ArrayList<>();

    public static DIAlarmFragment newInstance() {
        DIAlarmFragment fragment = new DIAlarmFragment();
        return fragment;
    }

    public static DIAlarmFragment newInstance(int viewPagerCurrentItem,String data) {
        DIAlarmFragment fragment = new DIAlarmFragment();
        fragment.atShowString = data;
        fragment.viewPagerCurrentItem = viewPagerCurrentItem;
        return fragment;
    }

    @Override
    public void initViews() {
        super.initViews();
        setContentView(R.layout.fragment_dialarm);
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new MyAdapter();
        recyclerView.setAdapter(adapter);
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        readData(viewPagerCurrentItem,atShowString);
    }


    //回读
    public void readData(int viewPagerCurrentItem,String _sConfigSMS) {
        if (TextUtils.isEmpty(_sConfigSMS) || viewPagerCurrentItem!=0) {
            return;
        }
        submitList.clear();
        BleLog.d("aaaaaaa===="+_sConfigSMS);
        if (_sConfigSMS != null && _sConfigSMS.trim().length() > 0 && isAdded()) {
            String[] splitConfigSMS = _sConfigSMS.split(";");
            if (splitConfigSMS.length == 2) {
                String sChannelOnOff = splitConfigSMS[0];
                if (sChannelOnOff.trim().length() == 0) {
                    //报警触发方式
                    List<String> diAlarmList = Arrays.asList(getResources().getStringArray(R.array.diAlarm));
                    submitList.add(new ParamListData("通道标识", 1, "关闭", diAlarmList, ""));
                } else {
                    //报警触发方式
                    if (sChannelOnOff.equals("0")) {
                        sChannelOnOff = "关闭";
                    } else if (sChannelOnOff.equals("1")) {
                        sChannelOnOff = "低电平";
                    } else {
                        sChannelOnOff = "高电平";
                    }
                    List<String> diAlarmList = Arrays.asList(getResources().getStringArray(R.array.diAlarm));
                    submitList.add(new ParamListData("通道标识", 1, ""+sChannelOnOff, diAlarmList, ""));
                }
                //报警内容
                String sAlarmContext = splitConfigSMS[1];
                submitList.add(new ParamListData("报警内容", 2, "" + sAlarmContext, "", ""));

            }else  {
                //报警触发方式
                List<String> diAlarmList = Arrays.asList(getResources().getStringArray(R.array.diAlarm));
                submitList.add(new ParamListData("通道标识", 1, "关闭", diAlarmList, ""));
                //报警内容
                submitList.add(new ParamListData("报警内容", 2, "", "", ""));
            }
            adapter.notifyDataSetChanged();
            recyclerView.setAdapter(adapter);
        }

    }

    //保存
    public ArrayList<ParamListData> saveOpearate(String interfaces,String sPassageWay) {
        ArrayList<ParamListData> resultList = new ArrayList<>();
        StringBuffer sb = new StringBuffer();
        for (ParamListData data : submitList) {
            String value = TextUtils.isEmpty(data.getValue()) ? data.getKey() : data.getValue();
            sb.append(value + ";");
        }
        if (TextUtils.isEmpty(sb.toString())){
            return resultList;
        }
        String[] splitConfigSMS = sb.toString().split(";");
        if (splitConfigSMS.length == 2) {
            String sChannelOnOff = splitConfigSMS[0];
            //报警触发方式
            if (sChannelOnOff.equals("关闭")) {
                sChannelOnOff = "0";
            } else if (sChannelOnOff.equals("低电平")) {
                sChannelOnOff = "1";
            } else {
                sChannelOnOff = "2";
            }
            resultList.add(new ParamListData("通道属性", HexUtil.strToHex("AT+CCFG=" + sPassageWay + "," + interfaces + "," + sChannelOnOff), "AT+CCFG"));
            String sAlarmContext = splitConfigSMS[1];
            try {
                if(sAlarmContext.length()>19){
                    resultList.clear();
                    showToast("报警内容不能大于19个");
                    return resultList;
                }
                resultList.add(new ParamListData("报警内容", HexUtil.chineseWordToGbk("AT+CATXT=" + sPassageWay + "," + sAlarmContext+"\r\n"), "AT+CATXT"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            //报警内容
        }
        return resultList;
    }

    public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {

        public MyAdapter() {

        }

        //创建新View，被LayoutManager所调用
        @Override
        public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.fragment_terminal_item, viewGroup, false);
            return new MyAdapter.ViewHolder(view);
        }


        //将数据与界面进行绑定的操作
        @Override
        public void onBindViewHolder(MyAdapter.ViewHolder viewHolder, int position) {
            viewHolder.list_item.setTag(position);
            viewHolder.bind(position);
        }

        //获取数据的数量
        @Override
        public int getItemCount() {
            return submitList == null ? 0 : submitList.size();
        }


        //自定义的ViewHolder，持有每个Item的的所有界面元素
        public class ViewHolder extends RecyclerView.ViewHolder {

            @BindView(R.id.list_item)
            LinearLayout list_item;
            @BindView(R.id.tv_name)
            TextView tvName;
            @BindView(R.id.edit_text)
            EditText editText;
            @BindView(R.id.img_spanner)
            ImageView imgSpanner;
            @BindView(R.id.tv_unit)
            TextView tvUnit;
            @BindView(R.id.switch_btn)
            SwitchButton switchBtn;

            public ViewHolder(View view) {
                super(view);
                ButterKnife.bind(this, view);
                EditTextUtil.setEditTextInhibitInputSpeChat(editText);
            }

            public void bind(int position) {
                ParamListData terminalListData = submitList.get(position);
                tvName.setText(terminalListData.getName());
                switch (terminalListData.getType()) {
                    case 1: //spinner
                        editText.setText("" + (TextUtils.isEmpty(terminalListData.getValue()) ? terminalListData.getKey() : terminalListData.getValue()));
                        editText.setHint("请选择" + terminalListData.getName());
                        imgSpanner.setVisibility(View.VISIBLE);
                        tvUnit.setVisibility(View.GONE);
                        switchBtn.setVisibility(View.GONE);
                        editText.setEnabled(false);//不可编辑
                        list_item.setBackgroundResource(R.color.white);
                        break;
                    case 2:  // edit
                        editText.setText("" + terminalListData.getValue());
                        editText.setHint("请输入" + terminalListData.getName());
                        tvUnit.setVisibility(View.VISIBLE);
                        tvUnit.setText(terminalListData.getUnit());
                        imgSpanner.setVisibility(View.GONE);
                        switchBtn.setVisibility(View.GONE);
                        editText.setEnabled(true);//可编辑
                        editText.setVisibility(View.VISIBLE);
                        list_item.setBackgroundResource(R.color.white);
                        break;
                }
                editText.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {

                    }

                    @Override
                    public void afterTextChanged(Editable s) {
                        int curPosition = getAdapterPosition();
                        ParamListData data = submitList.get(curPosition);
                        data.setValue(s.toString());
                    }
                });

                imgSpanner.setTag(terminalListData);
            }

            @OnClick(R.id.img_spanner)
            public void showSpanner(View v) {
                final ParamListData terminalListData = (ParamListData) v.getTag();
                OptionsPickerView pickerView = new OptionsPickerBuilder(mContext, new OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int options2, int options3, View v) {
                        editText.setText(terminalListData.getValues().get(options1));
                    }
                })
                        .setSubmitText("确定")//确定按钮文字
                        .setCancelText("取消")//取消按钮文字
                        .build();
                pickerView.setPicker(terminalListData.getValues());
                pickerView.show();
            }
        }
    }

}
